//
//  chatViewController.m
//  SoundPill
//
//  Created by 宋旭东 on 16/3/8.
//  Copyright © 2016年 宋旭东. All rights reserved.
//

#import "chatViewController.h"
#import "UUInputFunctionView.h"
#import "userInformationViewController.h"
#import "MJRefresh.h"
#import "UUMessageCell.h"
#import "ChatModel.h"
#import "UUMessageFrame.h"
#import "UUMessage.h"

#import "UIViewExt.h"
#import "AppDelegate.h"
@interface chatViewController ()<UUInputFunctionViewDelegate,UUMessageCellDelegate,UITableViewDataSource,UITableViewDelegate,EMChatManagerDelegate,MJRefreshBaseViewDelegate>
{
    
}
//@property (strong, nonatomic) NSMutableArray *contentArray;

@property (strong, nonatomic) MJRefreshHeaderView *header;
@property (strong, nonatomic) ChatModel *chatModel;
@property (strong, nonatomic) NSString *MessageID;
@property (strong, nonatomic) UITableView *chatTableView;
@end

@implementation chatViewController{
    UUInputFunctionView *IFView;
}
- (instancetype)init
{
    self = [super init];
    if (self) {

    }
    return self;
}
- (instancetype)initWithConversationChatter:(NSString *)conversationChatter conversationType:(EMConversationType)conversationType 
{
    if ([conversationChatter length] == 0) {
        return nil;
    }
    self = [super init];
    if (self) {
//        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            self.conversation = [[EMClient sharedClient].chatManager getConversation:conversationChatter type:conversationType createIfNotExist:YES];
            //        self.messsagesSource = [NSMutableArray array];
            [_conversation markAllMessagesAsRead];
            
//        });
        self.messageCountOfPage = 10;
    }
    return self;
}
- (void)checkMessageAvatar:(NSString *)avatarurl
{
    NSDictionary *chatDict = [[NSUserDefaults standardUserDefaults] valueForKey:[NSString stringWithFormat:@"chat%@",_conversation.conversationId]];
    if (!chatDict) {
        NSDictionary *chatUserInfo = [NSDictionary dictionaryWithObjectsAndKeys:avatarurl,@"chatAvatar",self.chatName,@"chatUsername", nil];
        [[NSUserDefaults standardUserDefaults] setObject:chatUserInfo forKey:[NSString stringWithFormat:@"chat%@",_conversation.conversationId]];
    }
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    //add notification
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tableViewScrollToBottom) name:UIKeyboardDidShowNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_conversation markAllMessagesAsRead];

    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
//    [[EMClient sharedClient].chatManager getConversation:self.chatId type:EMConversationTypeChat createIfNotExist:YES];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[EMClient sharedClient].chatManager removeDelegate:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    self.title = self.chatName;
    self.chatTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.height, self.view.frame.size.height - 45 - 64) style:UITableViewStylePlain];
    _chatTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _chatTableView.dataSource = self;
    _chatTableView.delegate = self;
    [self.view addSubview:_chatTableView];
    NSDictionary *chatDict = [[NSUserDefaults standardUserDefaults] valueForKey:[NSString stringWithFormat:@"chat%@",_conversation.conversationId]];
    UIImageView *chatBack = [[UIImageView alloc] initWithFrame:self.view.bounds];
    [chatBack setImageWithURL:[NSURL URLWithString:[chatDict valueForKey:@"chatAvatar"]] placeholderImage:[UIImage imageNamed:@"default_head"]];
//    _chatTableView.backgroundView = chatBack;
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    [back setFrame:CGRectMake(0, 0, 30, 30)];
    [back setImage:[UIImage imageNamed:@"backButton"] forState:UIControlStateNormal];
    [back addTarget:self action:@selector(backTo) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:back];
    self.navigationItem.leftBarButtonItem = backItem;
    [self addRefreshViews];
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self loadBaseViewsAndData];
        
//    });

//    self.contentArray = [NSMutableArray arrayWithObjects:@"如果时间是一种解药 也是我现在正服下的毒药",@"声音实验室",@"灵犀一点科技文化有限公司",@"我的天呐", nil];
}
- (void)backTo
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)addRefreshViews
{
    __weak typeof(self) weakSelf = self;
    self.header = [MJRefreshHeaderView header];
    _header.scrollView = self.chatTableView;
//    header.delegate = self;
    _header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        UUMessageFrame *frame = [weakSelf.chatModel.dataSource firstObject];
        [weakSelf tableViewDidTriggerHeaderRefresh:refreshView];
        NSUInteger index = [weakSelf.chatModel.dataSource indexOfObject:frame];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.chatTableView reloadData];
            [weakSelf.chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
            
            [weakSelf.header endRefreshing];
        });

//        [weakSelf.chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
        
//        [refreshView endRefreshing];

    };
//    _head = [MJRefreshHeaderView header];
//    _head.scrollView = self.chatTableView;
//    _head.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
//
//        
//        [weakSelf.head endRefreshing];
//    };

}
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
//    BOOL isHeader = [refreshView isKindOfClass:[MJRefreshHeaderView class]];
//    if (isHeader) {
        [self tableViewDidTriggerHeaderRefresh:refreshView];
//        page = 1; // 第一页
        
//        [_attenArray removeAllObjects];
//        [self AFNetworking:page refreshing:refreshView];
        [_header endRefreshing];
//        NSLog(@"%d", [_header isRefreshing]);
//    }
}
- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{
    
}

- (void)loadBaseViewsAndData
{
    self.chatModel = [[ChatModel alloc]init];
    self.chatModel.isGroupChat = NO;
//    [self.chatModel populateRandomDataSource];
    [self tableViewDidTriggerHeaderRefresh:_header];
    IFView = [[UUInputFunctionView alloc]initWithSuperVC:self];
    IFView.delegate = self;
    [self.view addSubview:IFView];
    
    [self.chatTableView reloadData];
    [self tableViewScrollToBottom];
//    [self tableViewScrollToBottom];
}
- (void)tableViewScrollToBottom
{
    if (self.chatModel.dataSource.count==0)
        return;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.chatModel.dataSource.count-1 inSection:0];
    [self.chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
#pragma mark - InputFunctionViewDelegate
- (void)UUInputFunctionView:(UUInputFunctionView *)funcView sendMessage:(NSString *)message
{

    NSString *from = [[EMClient sharedClient] currentUsername];
    NSDate *lastDate = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:lastDate];
    lastDate = [lastDate dateByAddingTimeInterval:interval];
    NSString *strDate = [NSString stringWithFormat:@"%@",lastDate];
    NSDictionary *dic = @{@"strContent": message,
                          @"type": @(UUMessageTypeText),@"strTime":strDate,@"strName":from};
//    IFView.TextViewInput.text = nil;
    [IFView changeSendBtnWithPhoto:YES];
    [self dealTheFunctionData:dic];
//    环信构建消息
    EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:message];
//生成文本Message
    EMMessage *EM_Message = [[EMMessage alloc] initWithConversationID:self.conversation.conversationId from:from to:self.conversation.conversationId body:body ext:nil];
    EM_Message.chatType = EMChatTypeChat;// 设置为单聊消息
//    环信发送消息
    [[EMClient sharedClient].chatManager asyncSendMessage:EM_Message progress:^(int progress) {
        
    } completion:^(EMMessage *message, EMError *error) {
        if (self.MessageID == nil) {
            self.MessageID = message.messageId;
        }
    }];
}

- (void)UUInputFunctionView:(UUInputFunctionView *)funcView sendPicture:(UIImage *)image
{
//    NSDictionary *dic = @{@"picture": image,
//                          @"type": @(UUMessageTypePicture)};
    NSString *from = [[EMClient sharedClient] currentUsername];
    NSDate *lastDate = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:lastDate];
    lastDate = [lastDate dateByAddingTimeInterval:interval];
    NSString *strDate = [NSString stringWithFormat:@"%@",lastDate];
    NSDictionary *dic = @{@"picture": image,
                          @"type": @(UUMessageTypePicture),@"strTime":strDate,@"strName":from};
    [self dealTheFunctionData:dic];
    
    
//    构造图片Message
    EMImageMessageBody *body = [[EMImageMessageBody alloc] initWithData:UIImagePNGRepresentation(image) displayName:@"image.png"];

//生成Message
    EMMessage *EM_Message = [[EMMessage alloc] initWithConversationID:self.conversation.conversationId from:from to:self.conversation.conversationId body:body ext:nil];
    EM_Message.chatType = EMChatTypeChat;
//    环信发送消息
    [[EMClient sharedClient].chatManager asyncSendMessage:EM_Message progress:^(int progress) {
        
    } completion:^(EMMessage *message, EMError *error) {
        
    }];
}

- (void)UUInputFunctionView:(UUInputFunctionView *)funcView sendVoice:(NSData *)voice time:(NSInteger)second
{
    NSDictionary *dic = @{@"voice": voice,
                          @"strVoiceTime": [NSString stringWithFormat:@"%d",(int)second],
                          @"type": @(UUMessageTypeVoice)};
    [self dealTheFunctionData:dic];
}

- (void)dealTheFunctionData:(NSDictionary *)dic
{
    [self.chatModel addSpecifiedItem:dic];
    [self.chatTableView reloadData];
    [self tableViewScrollToBottom];
}
#pragma mark - 环信回调
- (void)tableViewDidTriggerHeaderRefresh:(MJRefreshBaseView *)refreshView
{
    NSString *messageId = nil;
    if ([self.chatModel.dataSource count] > 0) {
        messageId = self.MessageID;//[(UUMessageFrame *)self.chatModel.dataSource.firstObject messageId];
        
    } else {
        messageId = nil;
    }
    [self _loadMessagesBefore:messageId count:self.messageCountOfPage append:YES];
}

- (void)_loadMessagesBefore:(NSString*)messageId
                      count:(NSInteger)count
                     append:(BOOL)isAppend
{
//    __weak typeof(self) weakSelf = self;
//    _messageQueue = dispatch_queue_create("easemob.com", NULL);
//    dispatch_async(_messageQueue, ^{
        NSArray *moreMessages = nil;
            moreMessages = [self.conversation loadMoreMessagesFromId:messageId limit:(int)count];
        
        if ([moreMessages count] == 0) {

            return;
        }
        [self didReceiveMessages:moreMessages];
        //从数据库导入时重新下载没有下载成功的附件
//        for (EMMessage *message in moreMessages)
//        {
//            [weakSelf _downloadMessageAttachments:message];
//        }
}

- (void)didReceiveMessages:(NSArray *)aMessages
{
    for (int index = 0; index < aMessages.count; index++) {
        
        EMMessage *message = aMessages[index];
        
        if ([message.conversationId isEqualToString:self.conversation.conversationId]) {
            if (index == 0) {
                self.MessageID = message.messageId;
            }
//            NSLog(@"------%@", message.messageId);
            double timeInterval =  message.timestamp ;
            if(timeInterval > 140000000000) {
                timeInterval = timeInterval / 1000;
            }
            NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
            [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
            NSString *time = [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timeInterval]];
            EMMessageBody *msgBody = message.body;
            switch (msgBody.type) {
                case EMMessageBodyTypeText:
                {
                    // 收到的文字消息
                    EMTextMessageBody *textBody = (EMTextMessageBody *)msgBody;
                    NSString *txt = textBody.text;
//                    NSLog(@"收到的文字是 txt -- %@",txt);
                    NSDictionary *dic = @{@"strContent":txt,@"type": @(UUMessageTypeText),@"strTime":time,@"strName":message.from};
                    if (_chatModel.dataSource.count == 0) {
                        if ([message.from isEqualToString: [[EMClient sharedClient] currentUsername]]) {
                            [self.chatModel addSpecifiedItem:dic];
                        } else {
                            [_chatModel addEachOtherItem:dic conversationid:self.conversation.conversationId messageID:message.messageId];
                        }
                        [self.chatTableView reloadData];
                        [self tableViewScrollToBottom];
                        
                    } else {
                        if (aMessages.count == 1) {
                            if ([message.from isEqualToString: [[EMClient sharedClient] currentUsername]]) {
                                [self.chatModel addSpecifiedItem:dic];
                            } else {
                                [_chatModel addEachOtherItem:dic conversationid:self.conversation.conversationId messageID:message.messageId];
                            }
                            [self.chatTableView reloadData];
                            [self tableViewScrollToBottom];
                            
                        } else {
                            if ([message.from isEqualToString: [[EMClient sharedClient] currentUsername]]) {
                                [self.chatModel insertSpecifiedItem:dic index:index];
                            } else {
                                [_chatModel insertEachOtherItem:dic conversationid:self.conversation.conversationId index:index];
                            }
                        }
                    }
                    
                    if (self.chatModel.dataSource.count == 0) {
                        [self.chatTableView reloadData];
                        [self tableViewScrollToBottom];
                    }
                }
                    break;
                case EMMessageBodyTypeImage:
                {
                    // 得到一个图片消息body
                    EMImageMessageBody *body = ((EMImageMessageBody *)msgBody);
//                    NSLog(@"大图remote路径 -- %@"   ,body.remotePath);
                    NSDictionary *dic = @{@"picture":body.thumbnailRemotePath,
                                          @"type": @(UUMessageTypePicture),@"strTime":time,@"strName":message.from};
                    
                    if (_chatModel.dataSource.count == 0) {
                        if (message.from == [[EMClient sharedClient] currentUsername]) {
                            [self.chatModel addSpecifiedItem:dic];
                        } else {
                            [_chatModel addEachOtherItem:dic conversationid:self.conversation.conversationId messageID:message.messageId];
                        }
                        [self.chatTableView reloadData];
                        [self tableViewScrollToBottom];
                        //                    [[EMClient sharedClient].chatManager asyncSendReadAckForMessage:message];
                    } else {
                        if (aMessages.count == 1) {
                            if (message.from == [[EMClient sharedClient] currentUsername]) {
                                [self.chatModel addSpecifiedItem:dic];
                            } else {
                                [_chatModel addEachOtherItem:dic conversationid:self.conversation.conversationId messageID:message.messageId];
                            }
                            [self.chatTableView reloadData];
                            [self tableViewScrollToBottom];
                        } else {
                            if (message.from == [[EMClient sharedClient] currentUsername]) {
                                [self.chatModel insertSpecifiedItem:dic index:index];
                            } else {
                                [_chatModel insertEachOtherItem:dic conversationid:self.conversation.conversationId index:index];
                            }
                        }
                        
                    }
                    
                    if (self.chatModel.dataSource.count == 0) {
                        [self.chatTableView reloadData];
                        [self tableViewScrollToBottom];
                    }
                    
                    
                    
                    
                    //                NSLog(@"大图local路径 -- %@"    ,body.localPath); // // 需要使用sdk提供的下载方法后才会存在
                    //                NSLog(@"大图的secret -- %@"    ,body.secretKey);
                    //                NSLog(@"大图的W -- %f ,大图的H -- %f",body.size.width,body.size.height);
                    //                NSLog(@"大图的下载状态 -- %lu",body.downloadStatus);
                    //
                    //
                    //                // 缩略图sdk会自动下载
//                                    NSLog(@"小图remote路径 -- %@"   ,body.thumbnailRemotePath);
                    //                NSLog(@"小图local路径 -- %@"    ,body.thumbnailLocalPath);
                    //                NSLog(@"小图的secret -- %@"    ,body.thumbnailSecretKey);
                    //                NSLog(@"小图的W -- %f ,大图的H -- %f",body.thumbnailSize.width,body.thumbnailSize.height);
                    //                NSLog(@"小图的下载状态 -- %lu",body.thumbnailDownloadStatus);
                }
                    break;
                    //            case EMMessageBodyTypeLocation:
                    //            {
                    //                EMLocationMessageBody *body = (EMLocationMessageBody *)msgBody;
                    //                NSLog(@"纬度-- %f",body.latitude);
                    //                NSLog(@"经度-- %f",body.longitude);
                    //                NSLog(@"地址-- %@",body.address);
                    //            }
                    //                break;
                    //            case EMMessageBodyTypeVoice:
                    //            {
                    //                // 音频sdk会自动下载
                    //                EMVoiceMessageBody *body = (EMVoiceMessageBody *)msgBody;
                    //                NSLog(@"音频remote路径 -- %@"      ,body.remotePath);
                    //                NSLog(@"音频local路径 -- %@"       ,body.localPath); // 需要使用sdk提供的下载方法后才会存在（音频会自动调用）
                    //                NSLog(@"音频的secret -- %@"        ,body.secretKey);
                    //                NSLog(@"音频文件大小 -- %lld"       ,body.fileLength);
                    //                NSLog(@"音频文件的下载状态 -- %lu"   ,body.downloadStatus);
                    //                NSLog(@"音频的时间长度 -- %lu"      ,body.duration);
                    //            }
                    //                break;
                    //            case EMMessageBodyTypeVideo:
                    //            {
                    //                EMVideoMessageBody *body = (EMVideoMessageBody *)msgBody;
                    //
                    //                NSLog(@"视频remote路径 -- %@"      ,body.remotePath);
                    //                NSLog(@"视频local路径 -- %@"       ,body.localPath); // 需要使用sdk提供的下载方法后才会存在
                    //                NSLog(@"视频的secret -- %@"        ,body.secretKey);
                    //                NSLog(@"视频文件大小 -- %lld"       ,body.fileLength);
                    //                NSLog(@"视频文件的下载状态 -- %lu"   ,body.downloadStatus);
                    //                NSLog(@"视频的时间长度 -- %lu"      ,body.duration);
                    //                NSLog(@"视频的W -- %f ,视频的H -- %f", body.thumbnailSize.width, body.thumbnailSize.height);
                    //                
                    //                // 缩略图sdk会自动下载
                    //                NSLog(@"缩略图的remote路径 -- %@"     ,body.thumbnailRemotePath);
                    //                NSLog(@"缩略图的local路径 -- %@"      ,body.thumbnailLocalPath);
                    //                NSLog(@"缩略图的secret -- %@"        ,body.thumbnailSecretKey);
                    //                NSLog(@"缩略图的下载状态 -- %lu"      ,body.thumbnailDownloadStatus);
                    //            }
                    //                break;
                    //            case EMMessageBodyTypeFile:
                    //            {
                    //                EMFileMessageBody *body = (EMFileMessageBody *)msgBody;
                    //                NSLog(@"文件remote路径 -- %@"      ,body.remotePath);
                    //                NSLog(@"文件local路径 -- %@"       ,body.localPath); // 需要使用sdk提供的下载方法后才会存在
                    //                NSLog(@"文件的secret -- %@"        ,body.secretKey);
                    //                NSLog(@"文件文件大小 -- %lld"       ,body.fileLength);
                    //                NSLog(@"文件文件的下载状态 -- %lu"   ,body.downloadStatus);
                    //            }
                    //                break;
                    
                default:
                    break;
            }
        }
        
    }
    for (EMMessage *Message in aMessages) {
        if (!Message.isReadAcked) {
            [[EMClient sharedClient].chatManager asyncSendReadAckForMessage:Message];
        }
    }
}
- (void)didUnreadMessagesCountChanged
{
    
}
#pragma mark - tableView delegate & datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.chatModel.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UUMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID"];
    if (cell == nil) {
        cell = [[UUMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellID"];
        cell.delegate = self;
    }
    [cell setMessageFrame:self.chatModel.dataSource[indexPath.row]];
//    if (indexPath.row % 2 == 0) {
//        cell.backgroundColor = [UIColor redColor];
//    } else {
//        cell.backgroundColor = [UIColor grayColor];
//    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self.chatModel.dataSource[indexPath.row] cellHeight];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.view endEditing:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

#pragma mark - cellDelegate
- (void)headImageDidClick:(UUMessageCell *)cell userId:(NSString *)userId{
    // headIamgeIcon is clicked
    MMDrawerController *drawer = (MMDrawerController *)[AppDelegate shareDelegate].window.rootViewController;
    UITabBarController *tab = (UITabBarController *)drawer.centerViewController;
    
    if (cell.messageFrame.message.strName == [[EMClient sharedClient] currentUsername]) {
        if (tab.selectedIndex == 4) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"stopAudioPlayer" object:nil];
//            NSLog(@"----%@",[tab selectedViewController]);
            UINavigationController *nav = [tab selectedViewController];
            [nav popToRootViewControllerAnimated:YES];
            [tab setSelectedIndex:4];
        } else {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"stopAudioPlayer" object:nil];
            
            [self.navigationController popToRootViewControllerAnimated:NO];
            [tab setSelectedIndex:4];
        }
    } else {
        userInformationViewController *otheruser = [[userInformationViewController alloc] initWithSelfUid:cell.messageFrame.message.strName];
        otheruser.isNeedPush = NO;
        //        UITabBarController *tab = (UITabBarController *)drawer.centerViewController;
        //        UINavigationController *nav= (UINavigationController *)tab.selectedViewController;
        [self.navigationController pushViewController:otheruser animated:YES];
    }
//    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:cell.messageFrame.message.strName message:@"headImage clicked" delegate:nil cancelButtonTitle:@"sure" otherButtonTitles:nil];
//    [alert show];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - 通知
-(void)keyboardChange:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];
    NSTimeInterval animationDuration;
    UIViewAnimationCurve animationCurve;
    CGRect keyboardEndFrame;
    
    [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
    [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:animationCurve];
    
    //adjust ChatTableView's height
    if (notification.name == UIKeyboardWillShowNotification) {
        _chatTableView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - keyboardEndFrame.size.height - 45);
        //        self.bottomConstraint.constant = keyboardEndFrame.size.height+40;
    }else{
        _chatTableView.frame =CGRectMake(0, 0, self.view.frame.size.height, self.view.frame.size.height - 45);
        //        self.bottomConstraint.constant = 40;
    }
    
    [self.view layoutIfNeeded];
    
    //adjust UUInputFunctionView's originPoint
    CGRect newFrame = IFView.frame;
    newFrame.origin.y = keyboardEndFrame.origin.y - newFrame.size.height;
    IFView.frame = CGRectMake(0, _chatTableView.bottom, self.view.width, 45);
    
    [UIView commitAnimations];
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
